package com.turing.usdtpay.mvp.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.turing.usdtpay.R;
import com.turing.usdtpay.base.BaseActivity;
import com.turing.usdtpay.entity.OrderInfoData;
import com.turing.usdtpay.http.ApiUrl;
import com.turing.usdtpay.mvp.contract.OrderInfoContract;
import com.turing.usdtpay.mvp.dialog.CancelOrderDialog;
import com.turing.usdtpay.mvp.presenter.OrderInfoPresenter;
import com.turing.usdtpay.mvp.view.BaseTitleView;
import com.turing.usdtpay.mvp.view.CircularProgressView;
import com.turing.usdtpay.utils.DateUtils;
import com.turing.usdtpay.utils.FileSizeUtils;
import com.turing.usdtpay.utils.FormatUtils;
import com.turing.usdtpay.utils.LogUtils;
import com.turing.usdtpay.utils.PhotoUtils;
import com.turing.usdtpay.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @作者：JAY
 * @创建时间：2019/10/11 11:17
 * @描述：
 **/
public class BuyOrderActivity extends Activity implements View.OnClickListener ,OrderInfoContract.View {
    private TextView mPrice,mName,mBank,mCard,mCopyName,mCopyBank,mCopyCard,mState;
    private TextView mOrderTv,mProportion,mUsdt,mTotal,mDeal,mComplete,mEmpty;
    private Bitmap bitmap;
    private BaseTitleView mTitle;
    private Button mUpLoad,mConfirm,mCancel,mWait,mConfirmCancel;
    private ImageView mPhoto;
    private int mSecond = 59,mMin = 1;
    private TextView mWarm ;
    private ClipboardManager mClipboard;
    private boolean isUpLoad = false;
    private LinearLayout mPayLayout;
    private OrderInfoContract.Present mPresent;
    private double mRate;
    private String mOrder = "";
    private ProgressBar mProgress;
    private CircularProgressView mCircularProgress;
    private CountDownTimer countDownTimer;
    private boolean isTimeOut = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_order);
        initView();
        initTitle();
        mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        setPresenter(new OrderInfoPresenter(this));
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        OrderInfoData data = (OrderInfoData) intent.getSerializableExtra("data");
        if (data != null){
            mProgress.setVisibility(View.GONE);
            mOrderTv.setText(data.getOrder());
            mOrder = data.getOrder();
            if (data.getStatus() == 0){
                mState.setText("待付款");
            }else if (data.getStatus() == 1){
                mState.setText("等待确认");
                mPayLayout.setVisibility(View.GONE);
                mWait.setVisibility(View.VISIBLE);
                mPhoto.setVisibility(View.VISIBLE);
                mUpLoad.setVisibility(View.GONE);
                String url = ApiUrl.API_DOWNLOAD_IMG + mOrder + ".jpg";
                LogUtils.d("url -->"+url);
                Picasso.get().load(url).into(mPhoto);
                mPhoto.setEnabled(false);
                mWarm.setVisibility(View.GONE);
            }else if (data.getStatus() == 2){
                mState.setText("已完成");
                mPhoto.setVisibility(View.VISIBLE);
                mUpLoad.setVisibility(View.GONE);
                String url = ApiUrl.API_DOWNLOAD_IMG + mOrder + ".jpg";
                LogUtils.d("url -->"+url);
                Picasso.get().load(url).into(mPhoto);
                mPhoto.setEnabled(false);
                mWarm.setVisibility(View.GONE);
            }else if (data.getStatus() == 3){
                mState.setText("已取消");
                mPayLayout.setVisibility(View.GONE);
                mEmpty.setVisibility(View.GONE);
                mConfirm.setVisibility(View.GONE);
                mConfirmCancel.setVisibility(View.VISIBLE);
                mWarm.setVisibility(View.GONE);
            }
            mRate = (double) data.getMoney_change_usdt()/100;
            mProportion.setText(FormatUtils.NoumberFromat2(mRate)+" CNY/USDT");
            mTotal.setText(FormatUtils.NoumberFromat2(((double) data.getMoney()/100))+" CNY");
            mUsdt.setText(FormatUtils.NoumberFromat8(((double) data.getMoney()/100)/mRate)+" USDT");

            mPrice.setText(FormatUtils.NoumberFromat2((double)data.getMoney()/100));
            mName.setText(data.getPay_bank_name());
            mBank.setText(data.getPay_bank());
            mCard.setText(data.getPay_bank_id());
            mDeal.setText(data.getCount_order_num()+"");
            mComplete.setText(FormatUtils.NoumberFromat2(((double)data.getCount_over_order_num()/(double) data.getCount_order_num())*100)+"%");


            Date date = new Date(System.currentTimeMillis()/1000);
            Date endDate = new Date(data.getOver_time());
            double second = DateUtils.getDistanceTimeSecond(date, endDate);
            if (second == 0){
                isTimeOut = true;
                mWarm.setVisibility(View.GONE);
            }else {
                isTimeOut = false;
                mMin = (int) (second/60);
                mSecond = (int) (second - (mMin *60));
                startCount((long) (second *1000));
            }
        }

    }


    private void initTitle() {
        mTitle.setLeftShow(true);
        mTitle.setLeftButtonListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitle.setTitle("确认订单");
    }

    private void initView() {
        mTitle = (BaseTitleView) findViewById(R.id.title);
        mUpLoad = (Button) findViewById(R.id.btn_upload);
        mPhoto = (ImageView) findViewById(R.id.iv_photo);
        mWarm = (TextView) findViewById(R.id.tv_warm);
        mPrice = (TextView) findViewById(R.id.tv_pay_price);
        mCopyName = (TextView) findViewById(R.id.tv_copy_name);
        mCopyBank = (TextView) findViewById(R.id.tv_copy_bank);
        mCopyCard = (TextView) findViewById(R.id.tv_copy_card);
        mName = (TextView) findViewById(R.id.tv_pay_name);
        mBank = (TextView) findViewById(R.id.tv_pay_bank);
        mCard = (TextView) findViewById(R.id.tv_pay_card);
        mConfirm = (Button) findViewById(R.id.btn_confirm);
        mCancel = (Button) findViewById(R.id.btn_cancel);
        mState = (TextView) findViewById(R.id.tv_state);
        mPayLayout = (LinearLayout) findViewById(R.id.pay_layout);
        mWait = (Button) findViewById(R.id.btn_wait);
        mOrderTv = (TextView) findViewById(R.id.tv_order);
        mProportion = (TextView) findViewById(R.id.tv_proportion);
        mUsdt = (TextView) findViewById(R.id.tv_usdt);
        mTotal = (TextView) findViewById(R.id.tv_total);
        mDeal = (TextView) findViewById(R.id.tv_deal);
        mComplete = (TextView) findViewById(R.id.tv_complete);
        mProgress = (ProgressBar) findViewById(R.id.progress);
        mConfirmCancel = (Button) findViewById(R.id.btn_confirm_cancel);
        mCircularProgress = (CircularProgressView) findViewById(R.id.circular_progress);
        mEmpty = (TextView) findViewById(R.id.tv_empty);

        mCopyName.setOnClickListener(this);
        mCopyBank.setOnClickListener(this);
        mCopyCard.setOnClickListener(this);
        mPhoto.setOnClickListener(this);
        mUpLoad.setOnClickListener(this);
        mConfirm.setOnClickListener(this);
        mCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == mUpLoad.getId()) {
            PhotoUtils.selectPic(this,0);
        }else if (v.getId() == mPhoto.getId()){
            PhotoUtils.selectPic(this,0);
        }else if (v.getId() == mCopyName.getId()){
            ClipData data = ClipData.newPlainText("bank",mName.getText().toString());
            mClipboard.setPrimaryClip(data);
            ToastUtils.showNormolToast(this,"复制成功");
        }else if (v.getId() == mCopyBank.getId()){
            ClipData data = ClipData.newPlainText("bank",mBank.getText().toString());
            mClipboard.setPrimaryClip(data);
            ToastUtils.showNormolToast(this,"复制成功");
        }else if (v.getId() == mCopyCard.getId()){
            ClipData data = ClipData.newPlainText("bank",mCard.getText().toString());
            mClipboard.setPrimaryClip(data);
            ToastUtils.showNormolToast(this,"复制成功");
        }else if (v.getId() == mConfirm.getId()){
            if (!isUpLoad){
                ToastUtils.showNormolToast(this,"请上传凭证");
                return;
            }
            if (isTimeOut){
                ToastUtils.showNormolToast(this,"已超时");
                return;
            }
            mProgress.setVisibility(View.VISIBLE);
            mPresent.confirmPay(this,mOrder);
        }else if (v.getId() == mCancel.getId()){
            CancelOrderDialog dialog = new CancelOrderDialog(this);
            dialog.setOnClickListener(new CancelOrderDialog.OnClickListener() {
                @Override
                public void onCancel() {
                    mProgress.setVisibility(View.VISIBLE);
                    mPresent.cancelOrder(BuyOrderActivity.this,mOrder);
                }
            });
            dialog.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PhotoUtils.PHOTO_CAMERA && resultCode == RESULT_OK) {
//            BitmapFactory.Options options = new BitmapFactory.Options();
//            options.inSampleSize = 2;
            bitmap = BitmapFactory.decodeFile(PhotoUtils.PhotoPath);
            if (bitmap != null) {
                mPhoto.setVisibility(View.VISIBLE);
                mUpLoad.setVisibility(View.GONE);
                mPhoto.setImageBitmap(bitmap);
                upLoadImg(mOrder,new File(PhotoUtils.PhotoPath));
            }

        } else if (requestCode == PhotoUtils.PHOTO_COLUMN && resultCode == RESULT_OK) {
            if (data != null){
                mPhoto.setVisibility(View.VISIBLE);
                mUpLoad.setVisibility(View.GONE);
                Uri uri = data.getData();
                Picasso.get().load(uri).into(mPhoto);
                String path = PhotoUtils.getRealPathFromUri(BuyOrderActivity.this, uri);    //获取文件真实地址
                upLoadImg(mOrder,new File(path));

            }
        }

    }

    private void upLoadImg(String order, File file) {
        try {
            double size = FileSizeUtils.FormetFileSize(FileSizeUtils.getFileSize(file), FileSizeUtils.SIZETYPE_MB);
            LogUtils.d("图片大小 -->"+size);
            if (size > 10){
                ToastUtils.showNormolToast(BuyOrderActivity.this,"图片不能超过10M，请重新选择");
                return;
            }
            mCircularProgress.setVisibility(View.VISIBLE);
            LogUtils.d("file -->"+file.getPath());
            mPresent.uploadPhoto(BuyOrderActivity.this,order,6,file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        if (bitmap != null){
            if (!bitmap.isRecycled()) {
                bitmap.recycle(); //回收图片所占的内存
                System.gc(); //提醒系统及时回收
            }
        }
        if (countDownTimer != null){
            countDownTimer.cancel();
            countDownTimer = null;
        }
        super.onDestroy();
    }

    @Override
    public void onSuccess(OrderInfoData data) {

    }

    @Override
    public void uploadSuccess(String url) {
        mCircularProgress.setVisibility(View.GONE);
        mCircularProgress.setProgress(0);
        ToastUtils.showNormolToast(this,"上传成功");
        isUpLoad = true;
    }

    @Override
    public void getSuccess() {

    }

    @Override
    public void paySuccess() {
        mProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this,"付款成功");
        mPayLayout.setVisibility(View.GONE);
        mWait.setVisibility(View.VISIBLE);
        Intent intent = new Intent();
        intent.putExtra("order",mOrder);
        setResult(1,intent);
        finish();
    }

    @Override
    public void cancelSuccess() {
        mProgress.setVisibility(View.GONE);
        mState.setText("已取消");
        mConfirmCancel.setVisibility(View.VISIBLE);
        ToastUtils.showNormolToast(this,"订单已取消");
        Intent intent = new Intent();
        intent.putExtra("order",mOrder);
        setResult(1,intent);
        finish();
    }

    @Override
    public void onFail(String msg) {
        mProgress.setVisibility(View.GONE);
        mCircularProgress.setVisibility(View.GONE);
        ToastUtils.showNormolToast(this,msg);
    }

    @Override
    public void onProgress(int progress) {
        mCircularProgress.setProgress(progress);
    }

    @Override
    public void setPresenter(OrderInfoContract.Present presenter) {
        mPresent = presenter;
    }

    private void startCount(long sum){
        countDownTimer = new CountDownTimer(sum,1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mSecond = --mSecond ;
                if (mSecond <0){
                    mMin = mMin - 1 ;
                    mSecond = 59;
                }
                String text = "请于<font color='#ff0000'>"+mMin+"分"+mSecond+"秒</font>支付，超时系统将会自动取消交易。";
                mWarm.setText(Html.fromHtml(text));
            }

            @Override
            public void onFinish() {
                mWarm.setText("倒数结束");

            }
        };
        countDownTimer.start();
    }
}
